{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "51134779",
   "metadata": {},
   "outputs": [],
   "source": [
    "#导入相关包以及导入冰湖环境\n",
    "import gym\n",
    "import numpy as np\n",
    "env = gym.make('FrozenLake-v1')\n",
    "#env.reset()\n",
    "#env.render()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0cb9a5e4",
   "metadata": {},
   "source": [
    " 由于gym环境更新，通过pip安装的gym包中已经没有FrozenLake-v0这个api了，所以使用的是最新发api：FrozenLake-v1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "15c43147",
   "metadata": {},
   "outputs": [],
   "source": [
    "#价值迭代函数\n",
    "def iteration(env, gamma = 0.99):\n",
    "    #初始化价值表\n",
    "    vlist = np.zeros(env.observation_space.n)\n",
    "\n",
    "    #设置收敛阈值参数\n",
    "    threshold = 1e-20\n",
    "\n",
    "    for i in range(100000):\n",
    "        new_vlist = np.copy(vlist)\n",
    "        #计算value，同时用最大值进行更新\n",
    "        for state in range(env.observation_space.n):\n",
    "            value = []\n",
    "            for action in range(env.action_space.n):\n",
    "                next_states_rewards = []\n",
    "                for next_sr in env.P[state][action]:\n",
    "                    trans_prob, next_state, reward_prob, _ = next_sr\n",
    "                    next_states_rewards.append((trans_prob * (reward_prob + gamma * new_vlist[next_state])))\n",
    "                value.append(np.sum(next_states_rewards))\n",
    "            vlist[state] = max(value)\n",
    "\n",
    "        #判定是否收敛\n",
    "        if (np.sum(np.fabs(new_vlist - vlist)) <= threshold):\n",
    "             print ('converged at iteration# %d.' %(i+1))\n",
    "             break\n",
    "\n",
    "    return vlist"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "811a0fe3",
   "metadata": {},
   "source": [
    "价值迭代函数如上，同时判定其在哪次迭代中收敛"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0c7969e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "#策略函数\n",
    "def policy(vlist, gamma=0.99):\n",
    "    \n",
    "    # 初始化策略\n",
    "    policy = np.zeros(env.observation_space.n)\n",
    "\n",
    "    for state in range(env.observation_space.n):\n",
    "\n",
    "        # 初始化Q值表\n",
    "        Q_table = np.zeros(env.action_space.n)\n",
    "\n",
    "        # 计算状态中的q值\n",
    "        for action in range(env.action_space.n):\n",
    "            for next_sr in env.P[state][action]:\n",
    "                trans_prob, next_state, reward_prob, _ = next_sr\n",
    "                Q_table[action] += (trans_prob * (reward_prob + gamma * vlist[next_state]))\n",
    "\n",
    "        # 选择q值最大的动作\n",
    "        policy[state] = np.argmax(Q_table)\n",
    "\n",
    "    return policy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a7101024",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "converged at iteration# 996.\n",
      "[0. 3. 3. 3. 0. 0. 0. 0. 3. 1. 0. 0. 0. 2. 1. 0.]\n"
     ]
    }
   ],
   "source": [
    "optimalfun = iteration(env=env, gamma=0.99)\n",
    "optimalpolicy = policy(optimalfun, gamma=0.99)\n",
    "\n",
    "print(optimalpolicy)"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "da0bda9a9f661c03497a74b8cba564b27cc7607e2b752504d47c30f08280d78f"
  },
  "kernelspec": {
   "display_name": "pytorch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
